package com.tanhua.sso.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.utils.JwtUtils;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference(version = "1.0.0")
    private UserApi userApi;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RSAService rsaService;


    public Object loginVerification(String phone, String verificationCode) {
        Boolean isNew = true;
        Long userId;
        String key = SmsService.REDIS_CODE + phone;
        String code = redisTemplate.opsForValue().get(key);
        //判断验证码输入是否正确
        if (!StrUtil.equals(verificationCode,code)){
            return ErrorResult.builder().errCode("500").errMessage("抱歉,验证码有误,请重试.").build();
        }
        //验证码正确 需要将验证码删除
        redisTemplate.delete(key);
        //查询是否为新用户
        User user = this.userApi.queryByMobile(phone);
        if (ObjectUtil.isNotNull(user)){
            isNew=false;
            userId=user.getId();
        }else {
            userId = this.userApi.save(phone);
        }
        //TODO jwt是一种规范使用RSA生成token

        Map<String, Object> claims = MapUtil.builder(new HashMap<String, Object>()).put("userId", userId).build();
        String token = JwtUtils.creatToken(claims,this.rsaService.getPrivateKeyStr(),24);
        //发送消息到rocketMQ通知其它系统
        try {
            Map<Object, Object> map = MapUtil.builder()
                    .put("userId", userId)
                    .put("date", System.currentTimeMillis())
                    .put("isNew", isNew).build();
            rocketMQTemplate.convertAndSend("tanhua-sso-login",map);
        } catch (MessagingException e) {
            log.error("发送登陆成功的消息到rocketMQ失败userID:{}",userId,e);
        }
        return MapUtil.builder().put("token",token).put("isNew",isNew).build();
    }


}
